package com.example.launibleplugin.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.launibleplugin.LaUniBlePlugin
import com.example.launibleplugin.model.BluetoothDevice
import com.example.launibleplugin.model.ConnectionState
import com.example.launibleplugin.utils.Logger
import com.google.gson.Gson

/**
 * 测量控制组件
 * Function: 提供呼吸家设备的测量控制功能
 * Parameter: plugin - 蓝牙插件实例
 * Parameter: connectedDevice - 已连接的设备
 * Parameter: isConnected - 连接状态
 * Note: 封装测量指令发送和数据接收功能
 */
@Composable
fun MeasurementControlComponent(
    plugin: LaUniBlePlugin,
    connectedDevice: BluetoothDevice?,
    isConnected: Boolean,
    modifier: Modifier = Modifier
) {
    var isMeasuring by remember { mutableStateOf(false) }
    var measurementData by remember { mutableStateOf(listOf<String>()) }
    var connectionStatus by remember { mutableStateOf("未连接") }
    var lastCommand by remember { mutableStateOf("") }
    var commandResponse by remember { mutableStateOf("") }
    var internalConnected by remember { mutableStateOf(false) }
    
    val context = LocalContext.current
    
    // 监听连接状态变化
    LaunchedEffect(isConnected, connectedDevice) {
        internalConnected = isConnected && connectedDevice != null
        Logger.d("MeasurementControl", "🔄 连接状态更新: isConnected=$isConnected, hasDevice=${connectedDevice != null}, internalConnected=$internalConnected")
        
        if (internalConnected) {
            connectionStatus = "✅ 已连接: ${connectedDevice?.getDisplayName()}"
        } else {
            connectionStatus = "❌ 未连接"
            isMeasuring = false // 断开连接时重置测量状态
        }
    }
    
    // 设置事件监听器
    LaunchedEffect(Unit) {
        // 连接状态变化监听
        plugin.setEventCallback("onConnectionStateChanged") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                if (data != null) {
                    val state = data["state"] as? String ?: "未知"
                    connectionStatus = when (state) {
                        "CONNECTING" -> "连接中..."
                        "CONNECTED" -> {
                            internalConnected = true
                            "已连接"
                        }
                        "DISCONNECTED" -> {
                            internalConnected = false
                            isMeasuring = false
                            "已断开"
                        }
                        else -> state
                    }
                    Logger.d("MeasurementControl", "连接状态变化: $connectionStatus, 内部状态: $internalConnected, 测量状态: $isMeasuring")
                }
            } catch (e: Exception) {
                Logger.e("MeasurementControl", "解析连接状态变化事件失败", e)
            }
        }
        
        // 设备连接成功监听
        plugin.setEventCallback("onDeviceConnected") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val device = data?.get("device") as? Map<String, Any>
                val deviceName = device?.get("deviceName") as? String ?: "未知设备"
                connectionStatus = "✅ 已连接: $deviceName"
                internalConnected = true
                Logger.i("MeasurementControl", "设备连接成功: $deviceName, 更新内部连接状态: $internalConnected")
            } catch (e: Exception) {
                Logger.e("MeasurementControl", "解析设备连接事件失败", e)
            }
        }
        
        // 设备断开连接监听
        plugin.setEventCallback("onDeviceDisconnected") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val device = data?.get("device") as? Map<String, Any>
                val deviceName = device?.get("deviceName") as? String ?: "未知设备"
                connectionStatus = "❌ 已断开: $deviceName"
                internalConnected = false
                isMeasuring = false // 断开连接时停止测量
                Logger.i("MeasurementControl", "设备断开连接: $deviceName, 重置内部连接状态: $internalConnected, 停止测量: $isMeasuring")
            } catch (e: Exception) {
                Logger.e("MeasurementControl", "解析设备断开事件失败", e)
            }
        }
        
        // 设备连接失败监听
        plugin.setEventCallback("onConnectionFailed") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val device = data?.get("device") as? Map<String, Any>
                val deviceName = device?.get("deviceName") as? String ?: "未知设备"
                val errorCode = data?.get("errorCode") as? Double ?: 0
                val errorMessage = data?.get("errorMessage") as? String ?: "未知错误"
                
                connectionStatus = "❌ 连接失败: $deviceName - $errorMessage"
                internalConnected = false
                isMeasuring = false
                
                Logger.e("MeasurementControl", "设备连接失败: $deviceName")
                Logger.e("MeasurementControl", "  错误码: ${errorCode.toInt()}")
                Logger.e("MeasurementControl", "  错误信息: $errorMessage")
                Logger.d("MeasurementControl", "  重置状态: internalConnected=$internalConnected, isMeasuring=$isMeasuring")
            } catch (e: Exception) {
                Logger.e("MeasurementControl", "解析设备连接失败事件异常", e)
                connectionStatus = "❌ 连接失败: 解析错误"
                internalConnected = false
                isMeasuring = false
            }
        }
        
        // 数据接收监听
        plugin.setEventCallback("onDataReceived") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                if (data != null) {
                    val dataType = data["dataType"] as? String ?: "未知类型"
                    val timestamp = System.currentTimeMillis()
                    val dataPoints = data["dataPoints"] as? List<Map<String, Any>> ?: emptyList()
                    
                    val dataInfo = buildString {
                        append("[${java.text.SimpleDateFormat("HH:mm:ss").format(timestamp)}] ")
                        append("数据类型: $dataType | ")
                        dataPoints.forEach { point ->
                            val metricName = point["metricName"] as? String ?: "未知指标"
                            val value = point["value"] as? Double ?: 0.0
                            val unit = point["unit"] as? String ?: ""
                            append("$metricName: $value $unit | ")
                        }
                    }
                    
                    measurementData = (measurementData + dataInfo).takeLast(20)
                    
                    // 控制台详细输出
                    Logger.i("MeasurementData", "📊 接收到测量数据:")
                    Logger.i("MeasurementData", "  数据类型: $dataType")
                    Logger.i("MeasurementData", "  时间戳: $timestamp")
                    dataPoints.forEachIndexed { index, point ->
                        val metricName = point["metricName"] as? String ?: "未知指标"
                        val value = point["value"] as? Double ?: 0.0
                        val unit = point["unit"] as? String ?: ""
                        Logger.i("MeasurementData", "  数据点${index + 1}: $metricName = $value $unit")
                    }
                }
            } catch (e: Exception) {
                Logger.e("MeasurementControl", "解析数据接收事件失败", e)
            }
        }
        
        // 测量指令响应监听
        plugin.setEventCallback("onMeasurementResponse") { jsonData ->
            try {
                val response = Gson().fromJson(jsonData, Map::class.java)
                val data = response["data"] as? Map<String, Any>
                val success = data?.get("success") as? Boolean ?: false
                val message = data?.get("message") as? String ?: "未知响应"
                
                commandResponse = if (success) "✅ $message" else "❌ $message"
                Logger.i("MeasurementCommand", "测量指令响应: success=$success, message=$message")
            } catch (e: Exception) {
                Logger.e("MeasurementControl", "解析测量指令响应失败", e)
            }
        }
    }
    
    Card(
        modifier = modifier.fillMaxWidth()
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "测量控制",
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 连接状态显示
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = if (internalConnected) {
                        MaterialTheme.colorScheme.primaryContainer
                    } else {
                        MaterialTheme.colorScheme.errorContainer
                    }
                )
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = if (internalConnected) "🟢" else "🔴",
                        style = MaterialTheme.typography.titleMedium
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = connectionStatus,
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 设备信息
            if (connectedDevice != null) {
                Text(
                    text = "设备: ${connectedDevice.getDisplayName()}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = "MAC: ${connectedDevice.macAddress}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                Spacer(modifier = Modifier.height(12.dp))
            }
            
            // 测量控制按钮
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Button(
                    onClick = {
                        Logger.d("MeasurementControl", "🔘 点击开始测量按钮")
                        Logger.d("MeasurementControl", "  isConnected: $isConnected")
                        Logger.d("MeasurementControl", "  internalConnected: $internalConnected")
                        Logger.d("MeasurementControl", "  connectedDevice: ${connectedDevice?.getDisplayName()}")
                        Logger.d("MeasurementControl", "  isMeasuring: $isMeasuring")
                        
                        if (connectedDevice != null && internalConnected) {
                            isMeasuring = true
                            lastCommand = "开始测量"
                            commandResponse = "发送中..."
                            
                            // 发送开始测量指令
                            val result = plugin.sendMeasurementCommand(
                                connectedDevice.deviceId,
                                1 // 开始测量命令码
                            )
                            
                            Logger.i("MeasurementCommand", "🚀 发送开始测量指令")
                            Logger.i("MeasurementCommand", "  设备ID: ${connectedDevice.deviceId}")
                            Logger.i("MeasurementCommand", "  设备名称: ${connectedDevice.getDisplayName()}")
                            Logger.i("MeasurementCommand", "  命令码: 1 (开始测量)")
                            Logger.d("MeasurementCommand", "  指令结果: $result")
                        } else {
                            Logger.w("MeasurementControl", "⚠️ 无法开始测量: 设备未连接或不可用")
                        }
                    },
                    enabled = internalConnected && !isMeasuring,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(if (internalConnected) "开始测量" else "设备未连接")
                }
                
                Button(
                    onClick = {
                        Logger.d("MeasurementControl", "🔘 点击停止测量按钮")
                        Logger.d("MeasurementControl", "  isConnected: $isConnected")
                        Logger.d("MeasurementControl", "  internalConnected: $internalConnected")
                        Logger.d("MeasurementControl", "  connectedDevice: ${connectedDevice?.getDisplayName()}")
                        Logger.d("MeasurementControl", "  isMeasuring: $isMeasuring")
                        
                        if (connectedDevice != null && internalConnected) {
                            isMeasuring = false
                            lastCommand = "停止测量"
                            commandResponse = "发送中..."
                            
                            // 发送停止测量指令
                            val result = plugin.sendMeasurementCommand(
                                connectedDevice.deviceId,
                                2 // 取消测量命令码
                            )
                            
                            Logger.i("MeasurementCommand", "🛑 发送停止测量指令")
                            Logger.i("MeasurementCommand", "  设备ID: ${connectedDevice.deviceId}")
                            Logger.i("MeasurementCommand", "  设备名称: ${connectedDevice.getDisplayName()}")
                            Logger.i("MeasurementCommand", "  命令码: 2 (停止测量)")
                            Logger.d("MeasurementCommand", "  指令结果: $result")
                        } else {
                            Logger.w("MeasurementControl", "⚠️ 无法停止测量: 设备未连接或不可用")
                        }
                    },
                    enabled = internalConnected && isMeasuring,
                    modifier = Modifier.weight(1f),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("停止测量")
                }
            }
            
            // 直接发送测量指令按钮（调试用）
            if (connectedDevice != null) {
                Spacer(modifier = Modifier.height(8.dp))
                
                Text(
                    text = "🔧 调试功能 - 直接发送指令（绕过握手）",
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    fontWeight = FontWeight.Medium
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(
                        onClick = {
                            Logger.d("MeasurementControl", "🔧 点击直接开始测量按钮")
                            Logger.d("MeasurementControl", "  设备ID: ${connectedDevice.deviceId}")
                            Logger.d("MeasurementControl", "  设备名称: ${connectedDevice.getDisplayName()}")
                            
                            lastCommand = "直接开始测量"
                            commandResponse = "发送中..."
                            
                            // 直接发送开始测量指令
                            val result = plugin.sendDirectMeasurementCommand(
                                connectedDevice.deviceId,
                                1 // 开始测量命令码
                            )
                            
                            Logger.i("MeasurementCommand", "🔧 直接发送开始测量指令")
                            Logger.i("MeasurementCommand", "  设备ID: ${connectedDevice.deviceId}")
                            Logger.i("MeasurementCommand", "  设备名称: ${connectedDevice.getDisplayName()}")
                            Logger.i("MeasurementCommand", "  命令码: 1 (开始测量)")
                            Logger.d("MeasurementCommand", "  指令结果: $result")
                        },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.tertiary
                        )
                    ) {
                        Text("直接开始测量")
                    }
                    
                    Button(
                        onClick = {
                            Logger.d("MeasurementControl", "🔧 点击直接停止测量按钮")
                            Logger.d("MeasurementControl", "  设备ID: ${connectedDevice.deviceId}")
                            Logger.d("MeasurementControl", "  设备名称: ${connectedDevice.getDisplayName()}")
                            
                            lastCommand = "直接停止测量"
                            commandResponse = "发送中..."
                            
                            // 直接发送停止测量指令
                            val result = plugin.sendDirectMeasurementCommand(
                                connectedDevice.deviceId,
                                2 // 取消测量命令码
                            )
                            
                            Logger.i("MeasurementCommand", "🔧 直接发送停止测量指令")
                            Logger.i("MeasurementCommand", "  设备ID: ${connectedDevice.deviceId}")
                            Logger.i("MeasurementCommand", "  设备名称: ${connectedDevice.getDisplayName()}")
                            Logger.i("MeasurementCommand", "  命令码: 2 (停止测量)")
                            Logger.d("MeasurementCommand", "  指令结果: $result")
                        },
                        modifier = Modifier.weight(1f),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.secondary
                        )
                    ) {
                        Text("直接停止测量")
                    }
                }
                
                // 测试可写特征按钮（调试用）
                Spacer(modifier = Modifier.height(8.dp))
                
                Button(
                    onClick = {
                        Logger.d("MeasurementControl", "🧪 点击测试可写特征按钮")
                        Logger.d("MeasurementControl", "  设备ID: ${connectedDevice.deviceId}")
                        Logger.d("MeasurementControl", "  设备名称: ${connectedDevice.getDisplayName()}")
                        
                        lastCommand = "测试可写特征"
                        commandResponse = "测试中..."
                        
                        // 测试所有可写特征
                        val result = plugin.testAllWritableCharacteristics(
                            connectedDevice.deviceId,
                            "db_sk_b1_ip,A325030015,1.0,1,1,\r\n" // 使用呼吸家协议的握手请求作为测试数据
                        )
                        
                        Logger.i("MeasurementCommand", "🧪 测试所有可写特征")
                        Logger.i("MeasurementCommand", "  设备ID: ${connectedDevice.deviceId}")
                        Logger.i("MeasurementCommand", "  设备名称: ${connectedDevice.getDisplayName()}")
                        Logger.d("MeasurementCommand", "  测试结果: $result")
                        
                        // 解析测试结果
                        try {
                            val response = Gson().fromJson(result, Map::class.java)
                            val success = response["success"] as? Boolean ?: false
                            val data = response["data"] as? Map<String, Any>
                            val successCount = data?.get("successCount") as? Double ?: 0.0
                            
                            commandResponse = if (success) {
                                "✅ 测试完成，找到 ${successCount.toInt()} 个可写特征"
                            } else {
                                "❌ 测试失败: ${response["message"]}"
                            }
                        } catch (e: Exception) {
                            commandResponse = "❌ 解析测试结果失败"
                            Logger.e("MeasurementControl", "解析测试结果失败", e)
                        }
                    },
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.outline
                    )
                ) {
                    Text("🧪 测试所有可写特征")
                }
            }
            
            // 指令状态显示
            if (lastCommand.isNotEmpty()) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "最后指令: $lastCommand",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                if (commandResponse.isNotEmpty()) {
                    Text(
                        text = "响应: $commandResponse",
                        style = MaterialTheme.typography.bodySmall,
                        color = if (commandResponse.startsWith("✅")) {
                            MaterialTheme.colorScheme.primary
                        } else if (commandResponse.startsWith("❌")) {
                            MaterialTheme.colorScheme.error
                        } else {
                            MaterialTheme.colorScheme.onSurfaceVariant
                        }
                    )
                }
            }
            
            // 测量数据显示
            if (measurementData.isNotEmpty()) {
                Spacer(modifier = Modifier.height(16.dp))
                
                Text(
                    text = "测量数据 (最近${measurementData.size}条)",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium
                )
                
                Spacer(modifier = Modifier.height(8.dp))
                
                LazyColumn(
                    verticalArrangement = Arrangement.spacedBy(4.dp),
                    modifier = Modifier.heightIn(max = 200.dp)
                ) {
                    items(measurementData.reversed()) { data ->
                        Card(
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            )
                        ) {
                            Text(
                                text = data,
                                modifier = Modifier.padding(8.dp),
                                style = MaterialTheme.typography.bodySmall
                            )
                        }
                    }
                }
            }
            
            // 使用说明和调试信息
            if (measurementData.isEmpty()) {
                Spacer(modifier = Modifier.height(16.dp))
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surfaceVariant
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp)
                    ) {
                        Text(
                            text = "📋 使用说明",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = "• 确保设备已连接后点击开始测量",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "• 测量数据会实时显示在下方列表中",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "• 详细数据可在控制台中查看",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        
                        // 调试信息
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = "🔧 调试信息",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "连接状态: $isConnected | 内部状态: $internalConnected",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "设备信息: ${connectedDevice?.getDisplayName() ?: "无"}",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "测量状态: ${if (isMeasuring) "进行中" else "未开始"}",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}